package com.ldn.basic.utils.tencent;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 李大牛家的牛 (scafel@163.com) 
 * @createDate 2024/8/5 - 13:44
 * @description ...
 **/
@Slf4j
public class WXBizDataCrypt {
    private String appid;
    private String sessionKey;

    public WXBizDataCrypt(String appid, String sessionKey) {
        this.appid = appid;
        this.sessionKey = sessionKey;
    }


    public JSONObject decrypt(String encryptedData, String iv) {
        if (StrUtil.length(sessionKey) != 24) {
            throw new RuntimeException("sessionKey长度错误");
        }
        if (StrUtil.length(iv) != 24) {
            throw new RuntimeException("iv长度错误");
        }
        try {
            byte[] sessionKeyBytes = Base64.decode(sessionKey);
            byte[] encryptedDataBytes = Base64.decode(encryptedData);
            byte[] ivBytes = Base64.decode(iv);
            AES aes = new AES("CBC", "PKCS7Padding", sessionKeyBytes, ivBytes);
            byte[] decrypted = aes.decrypt(encryptedDataBytes);
            String result = new String(decrypted);
            if (StrUtil.isBlank(result)){
                throw new RuntimeException("解密失败!");
            }
            JSONObject jsonObject = JSONUtil.parseObj(result);
            log.info("解密成功", jsonObject);
            return jsonObject;
        } catch (Exception e) {
            log.error("解密失败", e);
            throw new RuntimeException("解密失败!");
        }
    }
}
